package simi;

import java.util.List;
import java.util.Iterator;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class UserCommandServlet extends HttpServlet { 

	private static final int MAX_LEN = 500;
	private static final String NEWLINE = "\n";

	/**
	 * Need a UID to extend HttpServlet
	 */
	private static final long serialVersionUID = -2985631145912953308L;

	public void doPost(HttpServletRequest req, HttpServletResponse res) 
		throws ServletException, IOException { 
	
		// Get the user input
		String cmd = req.getParameter(Constants.USER_INPUT_PARAM);
		if(cmd != null){
			HttpSession theSession = req.getSession();
                        OutputStream os = (OutputStream) theSession
                                .getAttribute(Constants.SESSION_OUTPUT_STREAM);
			if(cmd.trim().length() == 0){
				// Push in a NEWLINE
		                os.write(NEWLINE.getBytes());
                		os.flush();
			}else{
        	        	ExpressionEvaluator ree = new ExpressionEvaluator();
                		InputStream is = (InputStream) theSession
               		         	 .getAttribute(Constants.SESSION_INPUT_STREAM);
                		ByteArrayOutputStream bos = (ByteArrayOutputStream) theSession
                        		 .getAttribute(Constants.RUNNING_OUTPUT_PARAM);
                		os.flush();
                		ree.setRInputStream(is);
                		ree.setROutputStream(os);
                		ree.setROutput(bos);
                		String result = ree.rEval(cmd);
			}
		}
	} 
}
